/* eslint-disable react/sort-comp */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Select, Spin, Row, Col, Tag } from 'antd';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import GeographicView from './GeographicView';
import styles from './style.less';

const { TextArea } = Input;
const FormItem = Form.Item;
const { Option } = Select;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
    md: { span: 10 },
  },
};

const submitFormLayout = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 10, offset: 7 },
  },
};

const brandList = [
  { code: 'sf', name: '顺丰' },
  { code: 'sto', name: '申通' },
  { code: 'zt', name: '中通' },
  { code: 'yt', name: '圆通' },
  { code: 'yd', name: '韵达' },
  { code: 'anekd', name: '安能' },
  // { code: "tt", name: "天天" },
  // { code: "ht", name: "百世" },
  { code: 'jt', name: '极兔' },
  // { code: 'zykd', name: '众邮' },
  { code: 'gt', name: '国通' },
];

@connect(({ loading, info, user, setting }) => ({
  user,
  info,
  ...setting,
  submitting: loading.effects['info/submit'],
}))
@Form.create()
export default class Info extends PureComponent {
  validatorGeographic = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length === 0) {
      callback('请选择完整的省市区');
      return;
    }
    callback();
  };

  componentDidMount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'info/getInfo',
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const { form, dispatch } = this.props;
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const { brand } = values;
        dispatch({
          type: 'info/submit',
          payload: {
            ...values,
            brand: brand.join(','),
          },
          then: () => {
            window.location.reload();
          },
        });
      }
    });
  };

  switchStatus = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'info/switchStatus',
      payload: { status: 'editor' },
    });
  };

  render() {
    const {
      form,
      submitting,
      info,
      options: { key },
    } = this.props;
    const { getFieldDecorator } = form;
    const { companyData = {}, status } = info;
    const { user_info = {}, brand_name = '' } = companyData;
    const { shortName = '' } = user_info;
    const isZyAccount = key == 'post' || key == 'yjy';
    const brandName = isZyAccount ? shortName : brand_name;

    const CompanyForm = data => {
      const formData = data || {};
      const {
        province = '',
        city = '',
        district = '',
        detail = '',
        phone = '',
        description = '',
        brand = '',
      } = formData;
      const area = formData.area ? formData.area : province ? [province, city, district] : [];
      return (
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label="公司名称">
            {getFieldDecorator('brand_name', {
              initialValue: brandName,
              rules: [
                {
                  required: true,
                  message: '请输入公司名称',
                },
              ],
            })(
              <Input
                size="large"
                maxLength={20}
                type="text"
                placeholder="公司名称"
                disabled={isZyAccount}
              />,
            )}
            {/* 中邮不能修改公司名称 */}
          </FormItem>
          <FormItem {...formItemLayout} label="公司省市">
            {getFieldDecorator('area', {
              initialValue: area,
              rules: [
                {
                  required: true,
                  message: '请选择省市区',
                },
                {
                  validator: this.validatorGeographic,
                },
              ],
            })(<GeographicView />)}
          </FormItem>
          <FormItem {...formItemLayout} label="详细地址">
            {getFieldDecorator('detail', {
              initialValue: detail,
              rules: [
                {
                  required: true,
                  message: '请输入详细地址',
                },
              ],
            })(<Input size="large" maxLength={50} type="text" placeholder="详细地址" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="负责人手机号">
            {getFieldDecorator('phone', {
              initialValue: phone,
              rules: [
                {
                  required: true,
                  message: '请输入负责人手机号',
                },
                phone,
              ],
              validateTrigger: 'onBlur',
            })(<Input size="large" type="text" placeholder="负责人手机号" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="运营快递品牌">
            {getFieldDecorator('brand', {
              initialValue: brand ? brand.split(',') : [],
              rules: [
                {
                  required: true,
                  message: '请选择快递品牌',
                },
              ],
            })(
              <Select mode="multiple" placeholder="选择品牌">
                {brandList.map(item => (
                  <Option key={item.code} value={item.code}>
                    {item.name}
                  </Option>
                ))}
              </Select>,
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="公司简介">
            {getFieldDecorator('description', {
              initialValue: description,
              rules: [
                {
                  required: false,
                },
                {
                  min: 10,
                  message: '描述信息不得少于10个字',
                },
                {
                  max: 200,
                  message: '描述信息不得超过200个字',
                },
              ],
              validateTrigger: 'onBlur',
            })(<TextArea style={{ minHeight: 32 }} placeholder="公司简介" rows={4} />)}
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button
              type="primary"
              size="large"
              htmlType="submit"
              style={{ width: '50%' }}
              loading={submitting}
            >
              确认
            </Button>
          </FormItem>
        </Form>
      );
    };

    const CompanyInfo = data => {
      const {
        detail,
        phone,
        brand,
        area,
        province = '-',
        city = '-',
        district = '-',
        description,
      } = data;
      const brands = brand || '';
      const names = brands.split(',').map(code => {
        const list = brandList.filter(item => item.code === code);
        return list.length > 0 ? list[0].name : '';
      });
      return (
        <Fragment>
          <Row>
            <Col span={7} style={{ textAlign: 'right' }}>
              公司名称：
            </Col>
            <Col span={17}>{brandName}</Col>
          </Row>
          <Row>
            <Col span={7} style={{ textAlign: 'right' }}>
              公司省市：
            </Col>
            <Col span={17}>{area ? area.join('/') : `${province}/${city}/${district}`}</Col>
          </Row>
          <Row>
            <Col span={7} style={{ textAlign: 'right' }}>
              详细地址：
            </Col>
            <Col span={17}>{detail}</Col>
          </Row>
          <Row>
            <Col span={7} style={{ textAlign: 'right' }}>
              负责人手机：
            </Col>
            <Col span={17}>{phone}</Col>
          </Row>
          <Row>
            <Col span={7} style={{ textAlign: 'right' }}>
              经营快递品牌：
            </Col>
            <Col span={17}>
              {names.map(bname => (
                <Tag key={bname}>{bname}</Tag>
              ))}
            </Col>
          </Row>
          <Row>
            <Col span={7} style={{ textAlign: 'right' }}>
              公司简介：
            </Col>
            <Col span={17}>{description || <span style={{ color: '#999999' }}>暂无设置</span>}</Col>
          </Row>
          <Row style={{ marginTop: 32 }}>
            <Col span={17} push={7}>
              <Button type="primary" size="large" onClick={this.switchStatus}>
                修改
              </Button>
            </Col>
          </Row>
        </Fragment>
      );
    };
    return (
      <PageHeaderLayout title="公司信息">
        <div className={styles.main}>
          <Spin spinning={status === 'loading'}>
            {status === 'loading' ? (
              <div style={{ padding: '40px 0' }} />
            ) : status === 'show' ? (
              CompanyInfo(companyData)
            ) : (
              CompanyForm(companyData)
            )}
          </Spin>
        </div>
      </PageHeaderLayout>
    );
  }
}
